#pragma once

#include <thread>
#include <queue>
#include <mutex>

#include <rtc_base/rtc_certificate.h>

#include "xrtcserver_def.h"
#include "base/event_loop.h"


namespace xrtc {

struct RtcServerOptions {
    int m_worker_num;
};

class RtcWorker;

class RtcServer {
public: 
    enum {
        QUIT = 0,
        RTC_MSG = 1
    };

    RtcServer();
    ~RtcServer();
    
    int init(const char* conf_file);
    bool start();
    void stop();
    int notify(int msg);
    void join();
    // 向消息队列中发送数据
    int sendRtcMsg(std::shared_ptr<RtcMsg> msg);
    void pushMsg(std::shared_ptr<RtcMsg> msg);
    std::shared_ptr<RtcMsg> popMsg();

    friend void rtcServerRecvNotify(EventLoop*, IOWatcher*, int, int, void*);

private:
    void _processNotify(int msg);
    void _stop();
    // 分发流消息给rtc_worker
    void _processRtcMsg();
    // 创建工作线程
    int _createWorker(int worker_id);
    // 通过stream_name获取分配的rtc_worker
    RtcWorker* _getWorker(const std::string& stream_name);
    // 生成校验ssl证书
    int _generate_and_check_certificate();


private:
    EventLoop* m_el;
    RtcServerOptions m_options;
    
    std::unique_ptr<std::thread> m_thread;

    IOWatcher* m_pipe_watcher = nullptr;
    int m_notify_recv_fd = -1;
    int m_notify_send_fd = -1;

    std::queue<std::shared_ptr<RtcMsg>> m_que_msg;
    std::mutex m_que_msg_mutex;

    std::vector<RtcWorker*> m_workers;

    rtc::scoped_refptr<rtc::RTCCertificate> m_certificate; // 指纹
};    
    
} // namespace xrtc 